package com.ysd.lis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.WkKnowledgeTestQuestion;
import com.ysd.lis.entity.WkTestOption;
import com.ysd.lis.entity.WkTestSmall;
import com.ysd.lis.mapper.WkTestSmallMapper;
import com.ysd.lis.request.CreateSmallQuestionParam;
import com.ysd.lis.service.WkKnowledgeTestQuestionService;
import com.ysd.lis.service.WkTestOptionService;
import com.ysd.lis.service.WkTestSmallService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 考试-小题表 服务实现类
 * </p>
 *
 * @author LiuQi
 * @since 2024-04-02
 */
@Service
public class WkTestSmallServiceImpl extends ServiceImpl<WkTestSmallMapper, WkTestSmall> implements WkTestSmallService {

    final String[] optionValue = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"};

    @Autowired
    WkTestSmallMapper wkTestSmallMapper;
    @Autowired
    WkKnowledgeTestQuestionService wkKnowledgeTestQuestionService;
    @Autowired
    WkTestOptionService wkTestOptionService;

    @Override
    public Result getSmallSubjectList(String paperId, String bigId) {
        LambdaQueryWrapper<WkTestSmall> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WkTestSmall::getBigSubjectId, bigId)
                .eq(WkTestSmall::getPaperId, paperId)
                .eq(WkTestSmall::getDelFlag, 0);
        List<WkTestSmall> wkTestSmalls = wkTestSmallMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", wkTestSmalls);
    }

    @Override
    public Result addTestSmallSubject(WkTestSmall wkTestSmall) {
        boolean save = this.save(wkTestSmall);
        if (save) {
            return Result.succ(1, "添加成功!", save);
        } else {
            return Result.fail("添加失败");
        }
    }

    @Override
    public Result editTestSmallSubject(WkTestSmall wkTestSmall) {
        boolean save = this.updateById(wkTestSmall);
        if (save) {
            return Result.succ(1, "编辑成功!", save);
        } else {
            return Result.fail("编辑失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result removeTestSmallSubject(WkTestSmall wkTestSmall) {
        boolean delete = this.removeById(wkTestSmall.getId());
        Map<String, Object> map = new HashMap();
        map.put("QUESTION_ID", wkTestSmall.getId());
        delete = delete && wkTestOptionService.removeByMap(map);
        if (delete) {
            return Result.succ(1, "编辑成功!", delete);
        } else {
            return Result.fail("编辑失败");
        }
    }

    /**
     * 通过知识库添加题目列表
     *
     * @param createSmallQuestionParam
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result createSmallByKnowledgeIds(CreateSmallQuestionParam createSmallQuestionParam) {
        List<WkKnowledgeTestQuestion> questionByPaper = wkKnowledgeTestQuestionService.getQuestionByPaper(createSmallQuestionParam);
        List<WkKnowledgeTestQuestion> anyList = getAny(questionByPaper, createSmallQuestionParam.getCount());
        // 插入前先清空大题数据
        clearQuestionAndOptionByBigId(createSmallQuestionParam.getBigSubjectId());
        // 插入问题表
        final AtomicInteger index = new AtomicInteger(1);
        List<WkTestSmall> smallList = anyList.stream().map(knowledgeTestQuestion -> {
            WkTestSmall wkTestSmall = new WkTestSmall();
            wkTestSmall.setPaperId(createSmallQuestionParam.getPaperId());
            wkTestSmall.setQuestionId(knowledgeTestQuestion.getId());
            wkTestSmall.setKnowledgeId(knowledgeTestQuestion.getKnowledgeId());
            wkTestSmall.setBigSubjectId(createSmallQuestionParam.getBigSubjectId());
            wkTestSmall.setQuestionType(createSmallQuestionParam.getQuestionType());
            wkTestSmall.setScore(createSmallQuestionParam.getScore());
            wkTestSmall.setQuestionName(knowledgeTestQuestion.getQuestionContent());
            wkTestSmall.setSeq(index.getAndAdd(1));
            wkTestSmall.setWkKnowledgeTestOptions(knowledgeTestQuestion.getOptionList());
            return wkTestSmall;
        }).collect(Collectors.toList());
        this.saveBatch(smallList);
        // 插入选项表
        List<WkTestOption> testOptionList = smallList.stream().map(question -> {
            List<String> collected = Arrays.stream(optionValue).limit(question.getWkKnowledgeTestOptions().size()).collect(Collectors.toList());
            Collections.shuffle(collected);
            if (question.getWkKnowledgeTestOptions().size() > 0) {
                final AtomicInteger value = new AtomicInteger(0);
                List<WkTestOption> collect = question.getWkKnowledgeTestOptions().stream().map(option -> {
                    WkTestOption wkTestOption = new WkTestOption();
                    wkTestOption.setPaperId(createSmallQuestionParam.getPaperId());
                    wkTestOption.setBigSubjectId(createSmallQuestionParam.getBigSubjectId());
                    wkTestOption.setQuestionId(question.getId());
                    wkTestOption.setOptionId(option.getId());
                    wkTestOption.setOptionValue(collected.get(value.getAndAdd(1)));
                    wkTestOption.setIsCorrect(option.getIsCorrect());
                    wkTestOption.setOptionContent(option.getOptionContent());
                    wkTestOption.setOptionType(createSmallQuestionParam.getQuestionType());
                    wkTestOption.setOptionKeyword(option.getOptionKeyword());
                    wkTestOption.setMatchType(option.getMatchType());
                    return wkTestOption;
                }).collect(Collectors.toList());
                question.setWkTestOptions(collect);
            }
            return question;
        }).flatMap(question -> question.getWkTestOptions().stream()).collect(Collectors.toList());
        wkTestOptionService.saveBatch(testOptionList);
        return Result.succ(1, "构建成功！", "");
    }

    /**
     * 根据大题id清空问题和选项表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearQuestionAndOptionByBigId(String bigId) {
        Map<String, Object> map = new HashMap();
        map.put("BIG_SUBJECT_ID", bigId);
        boolean b = this.removeByMap(map);
        return b && wkTestOptionService.removeByMap(map);
    }

    /**
     * 随机查过滤数据
     *
     * @param limit 随机条数
     * @return java.util.List<T>
     */
    public static <T> List<T> getAny(List<T> collection, Integer limit) {
        Integer total = 9;
        if (limit == null || limit <= 0 || total == 0) {
            return Collections.emptyList();
        }
        if (limit >= collection.size()) {
            return collection;
        }
        List<T> list = collection.stream()
                .skip(new Random().nextInt(collection.size() - limit))
                .limit(limit)
                .collect(Collectors.toList());
        return list;
    }
}
